package jmars.mobile.worker;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import jmars.mobile.common.Investigator;
import jmars.mobile.datainvestigation.Summary;
import jmars.mobile.domain.DateFeature;

public class SimpleDate implements Investigator {

	@Override
	public Long compute(File[] files, FileWriter writer) throws IOException, ParseException {
		Long total = 0L;
		FileInputStream fis;
		BufferedReader reader;
		String row;
		String[] cols;
		Map<Integer,DateFeature> stat=new HashMap<Integer,DateFeature>();
		DateFeature rowStat;
		SimpleDateFormat sdf = new SimpleDateFormat(Summary.dateFormat);
		Date temp;
		Long line;
		for(File inputFile:files){
			fis = new FileInputStream(inputFile);
			reader = new BufferedReader(new InputStreamReader(fis));
			line=0L;
			while((row=reader.readLine())!=null){
				line++;
				cols=row.split(Summary.columnSeperator);
				if(Summary.filterRow(cols,false,true)) continue;
				for(Integer idx:Summary.targetColumnIdx){
					if(idx<cols.length){
						if(stat.containsKey(idx))
							rowStat=stat.get(idx);
						else{
							rowStat = new DateFeature(Summary.dateFormat);
						}
						try{
							temp = sdf.parse(cols[idx]);
							rowStat.update(temp);
						}catch(Exception ex){
							System.out.println("exception at line "+line+" of "+inputFile.getName());
							System.out.println("data: "+cols[idx]);
							System.out.println(row);
							if(!Summary.errorResume){
								ex.printStackTrace();
								System.exit(0);
							}
						}
						stat.put(idx, rowStat);
					}
				}
				total++;
			}
			reader.close();
			fis.close();
			System.out.println(inputFile.getName()+" finished at "+total);
		}
		writer.write("%total:"+total+"\r\n");
		if(stat.size()<=1000){
			writer.write("%*****************details******************\r\n");
			for(Integer idx:stat.keySet()){
				writer.write(Summary.columns[idx]+","+stat.get(idx)+"\r\n");
			}
		}
		return total;
	}

}
